package com.javaee.xiangyang.controller.Android;

import com.javaee.xiangyang.common.ServiceResultEnum;
import com.javaee.xiangyang.entity.User;
import com.javaee.xiangyang.service.AccountService;
import com.javaee.xiangyang.vo.ServerResponse;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/User")
public class UserController {

    @Resource
    AccountService accountService;

    /**
     * 用户注册
     */
    @PostMapping("/UserRegister")
    public ServerResponse<User> register(User user) {
        if (accountService.AddUserService(user) != null) {
            return ServerResponse.creatServerResponseByFail(accountService.AddUserService(user).getResult());
        }
        return ServerResponse.creatServerResponseBySuccess();
    }

    /**
     * 用户登录
     */
    @GetMapping("/UserLogin")
    public ServerResponse<User> login(User user) {
        if (accountService.userLoginService(user) != ServiceResultEnum.LOGIN_SUCCESS) {
            return ServerResponse.creatServerResponseByFail(accountService.userLoginService(user).getResult());
        }
        return ServerResponse.creatServerResponseBySuccess();
    }

    /**
     * 获取用户相关信息
     */
    @GetMapping("/UserGet")
    public ServerResponse<User> getUser(User user) {
        if (accountService.GetUser(user) == null) {
            return ServerResponse.creatServerResponseByFail(ServiceResultEnum.LOGIN_NAME_NULL.getResult());
        }
        return ServerResponse.creatServerResponseBySuccess(accountService.GetUser(user));
    }

    /**
     * 手机修改用户个人信息
     */
    @PostMapping("/UserModify")
    public ServerResponse<User> userModify(User user) {
        if (accountService.userUpdateService(user).equals(ServiceResultEnum.LOGIN_NAME_NULL)) {
            return ServerResponse.creatServerResponseByFail(accountService.userLoginService(user).getResult());
        }
        return ServerResponse.creatServerResponseBySuccess();
    }

    /**
     * 手机修改个人头像
     */
    @PostMapping("/UserModifyHead")
    @Transactional
    public ServerResponse<User> UserModifyHead(MultipartFile file, String userAccount) throws IOException {
        User user = new User(userAccount);
        //保存图片
        String filename = file.getOriginalFilename();//这个是文件名称
        file.transferTo(new File("E:\\JSP\\xiangyang\\src\\main\\resources\\static\\Images\\userImages\\" + filename));
        user.setUserHead("\\userImages\\" + filename);
        if (accountService.userUpdateHead(user) == ServiceResultEnum.LOGIN_NAME_NULL) {
            return ServerResponse.creatServerResponseByFail(accountService.userLoginService(user).getResult());
        }
        return ServerResponse.creatServerResponseBySuccess();
    }

}
